import * as React from "react";
import { Form, Row, Col, Input, Button, Icon, DatePicker, Select, Table, Checkbox, message, Modal, InputNumber, ConfigProvider, Spin } from 'antd';
import { ColumnProps } from 'antd/es/table';
import * as moment from 'moment';
import './index.scss';

import { FormComponentProps } from 'antd/lib/form/Form' //获取form表单的interface

import zhCN from 'antd/es/locale/zh_CN';
import { Link } from "react-router-dom";
// 检索
import { CAMLFilter, CAMLCompare, CamlQuery, SPDataType, CamlParam, CamlOrderBy } from './../../config/CAMLHelper';

// 台账合同
import { ListGUID } from '../../config/ListGuid';
import Api from '../../config/api';
import { isHavePermission, isHavePathPermission } from '../../utils/utils'
import { dynamicsService } from "../../../../../services/services";

interface DataType {
  key: React.Key;
  number: string;
  name: string;
  handle: string;
  relative: string;
  dependent: string;
  // time: string;
}
interface fromdata {
  field: string;
  text: string;
  errorMessage: string;
  required: boolean;
  type: string;
  value: any;
  options: any;
  theType: any;
  header: any;
  conditions: any;
}
const { Option } = Select;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const columns: ColumnProps<DataType>[] = [
  {
    title: '合同编号',
    dataIndex: 'Title',
    key: 'Title',
    align: 'center',
    render(text, record: any) {
      if (record.DataType == '合同') {
        return (
          <div>
            {
              <Link to={{  pathname: record.Title.split('-').length > 0 && record.Title.split('-')[1] != '0' && !record.Title.includes('DUMY') ? "AddContractVersion" : "AddContractNo", state: { id: text, backPage: 'SearchContract' } }}>{text}</Link>
            }
          </div>
        )
      } else {
        return (<div>{text}</div>)
      }
    },
  },
  {
    title: '合同名称',
    dataIndex: 'ContractName',
    key: 'ContractName',
    align: 'center',
    render(text, recod: any) {
      return (
        <div>
          <span>{recod.DataType === '申请书' ? recod.filename : recod.ContractName}</span>
        </div>
      )
    },
  },
  {
    title: '合同内容',
    dataIndex: 'handle',
    key: 'handle',
    align: 'center',
    render(text, recod: any) {
      return (
        <div>

          <span>{recod.DataType === '申请书' ? '申请人' : '依赖者名'}:{recod.DataType === '申请书' ? (recod.apply_user_nm || recod.AuthorName) : recod.RelierName};{recod.DataType === '申请书' ? '对方公司名称' : '所属公司'}:{recod.DataType === '申请书' ? recod.company_name : recod.BelongsCompany};</span>
        </div>
      )
    },

  }, {
    title: '相对方',
    dataIndex: 'Counterparty',
    key: 'Counterparty',
    align: 'center',
    render(text, recod: any) {
      return (
        <div>
          <span>{recod.DataType === '申请书' ? recod.company_name : recod.Counterparty}</span>
        </div>
      )
    },
  },
  {
    title: '分类',
    dataIndex: 'DataType',
    key: 'DataType',
    align: 'center',
    render(text, recod: any) {
      return (
        <div>
          <span>{recod.DataType}</span>
        </div>
      )
    },
  },
  {
    title: '附件',
    dataIndex: 'file',
    key: 'file',
    align: 'center',
    render: relative => (
      <div>
        {relative && relative.map(tag => {
          const dispUrl = ListGUID.DocumentLink;
          const splitName = tag.Name.split('.');
          return (
            <div key={tag}>
              {
                splitName[splitName.length - 1] === 'xlsx' || splitName[splitName.length - 1] === 'xls' || splitName[splitName.length - 1] === 'docx' || splitName[splitName.length - 1] === 'doc' ? <a href={dispUrl + '?sourcedoc=' + tag.UniqueId} target="_blank">{tag.Name}</a> : <a href={tag.ServerRelativeUrl} download={tag.Name} target="_blank">{tag.Name}</a>
              }

            </div>
          );
        })}
      </div>
    ),
  }
]
const fromData: fromdata[] = [
  {
    field: 'bianhao',
    text: '合同编号',
    errorMessage: '请选择日期',
    required: false,
    type: 'bianhao',
    value: null,
    options: [],
    theType: 'bianhao',
    header: "LastAnswerTime",
    conditions: "Eq",
  }, {
    field: 'jobid',
    text: '语言',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: "Language",
    conditions: "Contains",
  }, {
    field: 'chuangjian',
    text: '创建日期',
    errorMessage: '请选择日期',
    required: false,
    type: 'chuangjian',
    value: null,
    options: [],
    theType: 'chuangjian',
    header: "LastAnswerTime",
    conditions: "Eq",
  }, {
    // field: 'nature',
    field: 'customer',
    text: '问题',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Number',
    header: "Contractualproblems",
    conditions: "Eq",
  }, {
    field: 'date1',
    text: '法务受理日',
    errorMessage: '请选择日期',
    required: false,
    type: 'date1',
    value: null,
    options: [],
    theType: 'DateTime',
    header: "AcceptTime",
    conditions: "Ge",
  }, {
    field: 'nature',
    text: '合同性质',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Number',
    header: "ContractNature",
    conditions: "Eq",
  }, {
    field: 'date',
    text: '法务最后回答日',
    errorMessage: '请选择日期',
    required: false,
    type: 'date',
    value: null,
    options: [],
    theType: 'DateTime',
    header: "LastAnswerTime",
    conditions: "Ge",
  }, {
    field: 'term',
    text: '合同期限',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Number',
    header: "ContractDeadline",
    conditions: "Eq",
  }, {
    field: 'mingcheng',
    text: '合同名称',
    errorMessage: '请选择日期',
    required: false,
    type: 'mingcheng',
    value: null,
    options: [],
    theType: 'mingcheng',
    header: "LastAnswerTime",
    conditions: "Contains",
  }, {
    field: 'importance',
    text: '合同重要性',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Number',
    header: "ContractName",
    conditions: "Eq",
  }, {
    field: 'username',
    text: '关键词1',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: "Keyword1",
    conditions: "Contains",
  }, {
    field: 'modify',
    text: '合同修改性质',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: "ContactEditNature",
    conditions: "Contains",
  }, {
    field: 'username2',
    text: '关键词2',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: "Keyword2",
    conditions: "Contains",
  }, {
    field: 'Qualifications',
    text: '资质',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "Qualifications",
    conditions: "Eq",
  }, {
    field: 'Our',
    text: '我方',
    errorMessage: '请选择',
    required: false,
    type: 'selectss',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "Our",
    conditions: "Eq",
  }, {
    field: 'HasReviewOpinion',
    text: '审核意见书',
    errorMessage: '请选择',
    required: false,
    type: 'selects',
    value: undefined,
    options: [{ Title: '有' }, { Title: '无' }],
    theType: 'Text',
    header: "HasReviewOpinion",
    conditions: "Eq",
  }, {
    field: 'xiangduifang',
    text: '相对方',
    errorMessage: '请选择日期',
    required: false,
    type: 'xiangduifang',
    value: null,
    options: [],
    theType: 'xiangduifang',
    header: "LastAnswerTime",
    conditions: "Contains",
  }, {
    field: 'Lawyerreview',
    text: '律师审查',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Number',
    header: "LawyerReviewID",
    conditions: "Eq",
  }, {
    field: 'relyOn',
    text: '社内依赖者名',
    errorMessage: '请输入',
    required: false,
    type: 'char1',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "RelierName",
    conditions: "Contains",
  }, {
    field: 'number',
    text: '裁决编号',
    errorMessage: '请输入编号',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: "RuleNumber",
    conditions: "Eq",
  },
  {
    field: 'company',
    text: '所属公司',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "BelongsCompany",
    conditions: "Eq",
  },{
    field: 'tobear',
    text: '审查担当',
    errorMessage: '请选择',
    required: false,
    type: 'multiSelect',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "ReviewOnID",
    conditions: "Eq",
  }, {
    field: 'department',
    text: '所属部门',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "BelongsDepartment",
    conditions: "Eq",
  }, {
    field: 'tobear',
    text: '审查担当',
    errorMessage: '请选择',
    required: false,
    type: 'multiSelect',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "ReviewOnID",
    conditions: "Eq",
  } // 其他
  , {
    field: 'Other',
    text: '其他',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: undefined,
    options: [],
    theType: 'Text',
    header: "Other",
    conditions: "Contains",
  }
]
const data: DataType[] = [
  {
    key: '1',
    number: 'S s 20200202-01',
    name: 'xxxxxxx合同1',
    handle: '2022-01-01 ~ 2022-02-02',
    relative: '合同相关内容',
    dependent: 'xxxxxx软件开发合同',
  },
  {
    key: '2',
    number: 'B s 20200202-01',
    name: 'xxxxxxx合同2',
    handle: '2022-01-01 ~ 2022-02-02',
    relative: '合同相关内容',
    dependent: 'xxxxxx软件开发合同',
  },
  {
    key: '3',
    number: 'M s 20200202-01',
    name: 'xxxxxxx合同3',
    handle: '2022-01-01 ~ 2022-02-02',
    relative: '合同相关内容',
    dependent: 'xxxxxx软件开发合同',
  },
];

const formItemLayout = {
  labelCol: {
    span: 7,

  },
  wrapperCol: {
    offset: 0,
    span: 17,
  },
}
// 多选
const CheckboxGroup = Checkbox.Group;
// 选项所有数据
const plainOptions = ['仅合同', '仅申请书'];
// 选中数组
const defaultCheckedList = ['仅合同', '仅申请书'];
// export default class SearchContract extends React.Component {
class SearchContract extends React.Component<FormComponentProps> {
  constructor(props: any & FormComponentProps) {
    super(props);
  }
  list = ['测试数据', '测试数据1'];
  state = {
    ces: '1',
    filter: [{
      logic: "and",
      where: [

      ]
    }],
    pager: {
      current: 1,
      size: 10
    },

    time1: 0,
    time2: 0,
    time3: 0,
    time4: 0,
    time5: 0,
    time6: 0,
    time7: 0,
    time8: 0,
    ToTheTotal: [],
    loading: false,
    inSearchOf: false,
    checkedList: defaultCheckedList,
    // 多选初始选中状态
    indeterminate: false,
    // 是否全选状态
    checkAll: false,
    //表单数据对象
    local: zhCN,
    arr: '',
    // 记录条件个数
    arrSize: 0,
    data: [],
    // 全部的合同数据
    allData: [],
    // 全部的申请书数据
    allData1: [],
    size: '',
    // 总数据
    totalnumber: [],
    // 总数据数
    totalnum: 0,
    //表单数据对象
    retrieveList: [],
    form: {
      // 合同名称
      theContract: null,
      // 相对方
      otherSide: null,
      // 合同编号1
      contract1: null,
      // 合同编号2
      contract2: null,
      // 创建日期
      dateOf: "",
      // 结束时间
      dateOf1: "",
      dateOf2: "",
      dateOf3: "",
      // 合同名称
      contractName: null,
      // 我方
      min: undefined,
      // 审查担当
      personreview: undefined,
      list: [],

    },
    visible: false,
    confirmLoading: false,
    //审查担当
    personreviewList: [],
    weList: []

  }

  //动态更新绑定数据
  public async componentDidMount() {
    isHavePathPermission()
    

    let isBack:any;
    isBack = this.props;
    // 
    
    if (isBack.location.state != undefined) {
      let form = JSON.parse(localStorage.getItem('searchForm'));
      let formParams = JSON.parse(localStorage.getItem('searchFormParams'));
      let checkedList = JSON.parse(localStorage.getItem('checkedList'));
      let checkAll = JSON.parse(localStorage.getItem('checkAll'));
      let indeterminate = JSON.parse(localStorage.getItem('indeterminate'));
      let PageIndex = JSON.parse(localStorage.getItem('PageIndex')); // 页码
      let pager = this.state.pager;
      pager.current = PageIndex;
      this.setState(pager);

      
      
      
      
      if(form != null){
        this.setState({form, checkedList, checkAll, indeterminate},()=>{
          this.retrieve('检索', 1);
        });
      }else if(formParams != null){
        let params = formParams[0].where;
        this.setParamsByCache(params); //高级检索缓存赋值
        this.theQuery(formParams, 1);
      }else{
        // localStorage.removeItem('searchForm'); 
        // localStorage.removeItem('searchType');
        // localStorage.removeItem('searchFormParams');
        this.getData();
      }
      // this.setState({ form })
    }else{
      localStorage.removeItem('searchForm');
      localStorage.removeItem('searchType');
      localStorage.removeItem('searchFormParams');
      fromData.forEach((item, index)=>{
        fromData[index].value = undefined
      })
      
      this.getData();
    }


    this.getTest();// 测试代码，调试API使用
    let token = await dynamicsService.getToken()
    //
    let getlist = await dynamicsService.getusers(token.data.data)
    fromData[18].options = getlist.value
  }

  setParamsByCache(params:any) {
    let form = this.state.form;

    fromData.forEach((item, index)=>{
      fromData[index].value = undefined
    })

    params.forEach(function(item, index) {
      let key = item.key;
      let type = item.filterType;
      let value = item.value;
      for(let i = 0; i < fromData.length; i++){
        let field = fromData[i].field;

        if(key == '' && type == 'ContractNum'){ //合同编号
          if (value.indexOf('|') > -1) {
            let num = value.split('|');
            form.contract1 = num[0];
            form.contract2 = num[1];
          }else{
            form.contract1 = value;
          }
          
        }else if(key == 'Language' && field == 'jobid'){ //语言
          fromData[i].value = value;
        }else if(key == 'Created' && type == 'Ge'){ //创建时间
          form.dateOf2 = value;
        }else if(key == 'Created' && type == 'Le'){ //创建时间
          form.dateOf3 = value;
        }else if(key == 'Contractualproblems' && field == 'customer'){ //问题
          fromData[i].value = value;
        }else if(key == 'AcceptTime' && field == 'date1'){ //法务受理日
          fromData[i].value = moment(value, "YYYY-MM-DD")
        }else if(key == 'ContractNature' && field == 'nature'){ //合同性质
          fromData[i].value = value;
        }else if(key == 'LastAnswerTime' && field == 'date'){ //法务最后回答日
          fromData[i].value = moment(value, "YYYY-MM-DD")
        }else if(key == 'ContractDeadline' && field == 'term'){ //合同期限
          fromData[i].value = value;
        }else if(key == 'ContractName' && field == 'mingcheng' && type == 'Contains'){ //合同名称
          form.contractName = value;
        }else if(key == 'ContractName' && field == 'importance' && type == 'Eq'){ //合同重要性              
          fromData[i].value = value;
        }else if(key == 'Keyword1' && field == 'username'){ //关键词1
          fromData[i].value = value;
        }else if(key == 'ContactEditNature' && field == 'modify'){ //合同修改性质
          fromData[i].value = value;
        }else if(key == 'Keyword2' && field == 'username2'){ //关键词2
          fromData[i].value = value;
        }else if(key == 'Qualifications' && field == 'Qualifications'){ //资质
          fromData[i].value = value;
        }else if(key == 'Our' && field == 'Our'){ //我方
          fromData[i].value = value;
        }else if(key == 'HasReviewOpinion' && field == 'HasReviewOpinion'){ //审核申请书
          fromData[i].value = value;
        }else if(key == 'Counterparty' && field == 'xiangduifang'){ //相对方
          form.otherSide = value;
        }else if(key == 'LawyerReviewID' && field == 'Lawyerreview'){ //律师审查
          fromData[i].value = value;
        }else if(key == 'RelierName' && field == 'relyOn'){ //社内依赖者名
          fromData[i].value = value;
        }else if(key == 'RuleNumber' && field == 'number'){ //决裁号
          fromData[i].value = value;
        }else if(key == 'BelongsCompany' && field == 'company'){ //所属公司
          fromData[i].value = value;
        }else if(key == 'Other' && field == 'Other'){ //其他
          fromData[i].value = value;
        }else if(key == 'BelongsDepartment' && field == 'department'){ //所属部门
          fromData[i].value = value;
        }else if(key == 'ReviewOnID' && field == 'tobear'){ //审查担当
          // let arr = fromData[i].value == undefined || fromData[i].value == null ? [] : fromData[i].value;
          // arr.push(value);
          let valArr = [];
          valArr = value.split(';');
          fromData[i].value = valArr;
        }
      }
    });
    this.setState({form},()=>{
      
      
    });
  }

  /**
   * 根据后台返回的 data 中 type 类型生成不同的组件
   * @param item  json
   * @param Component
   */
  switchItem(item) {
    let defaultDateValue = [];
    if(this.state.form.dateOf2 != "" && this.state.form.dateOf3 != null){
      
      defaultDateValue = [
        moment(this.state.form.dateOf2, dateFormat),
        moment(this.state.form.dateOf3, dateFormat),
      ];
    }
    const type = item.type;
    switch (type) {
      case 'Picker':
        return <RangePicker allowClear format={dateFormat} placeholder={['选择开始日期', '选择结束日期']} />;
      case 'int':
        return <InputNumber style={{ width: '100%' }} />;
      case 'char':
        return <Input allowClear style={{ width: '100%' }} placeholder={item.errorMessage} />;
      case 'char1':
        return <Input allowClear placeholder="请输入内容"
          onChange={(event) => { this.allowClear(event, "community") }}
          onBlur={(event) => { this.loseFocus(event, "community") }} />
      case 'date':
        return <DatePicker allowClear format={dateFormat} style={{ width: '100%' }} placeholder={item.errorMessage} />;
      case 'date1':
        return <DatePicker allowClear format={dateFormat} style={{ width: '100%' }} placeholder={item.errorMessage} />;

      case 'select':
        return (
          <Select allowClear style={{ width: '100%' }} placeholder={item.errorMessage}>
            {
              item.options.map((option, index) => {
                return (<Option value={option.ID} key={option.Title}>{option.Title}</Option>)
              })
            }
          </Select>
        )
      case 'selects':
        return (
          <Select allowClear style={{ width: '100%' }} placeholder={item.errorMessage}>
            {
              item.options.map((option, index) => {
                return (<Option value={option.Title} key={option.Title}>{option.Title}</Option>)
              })
            }
          </Select>
        )
        case 'selectss':
        return (
          <Select allowClear style={{ width: '100%' }} placeholder={item.errorMessage}>
            {
              item.options.map((option, index) => {
                return (<Option value={option} key={option}>{option}</Option>)
              })
            }
          </Select>
        )
      case 'searchThe':
        return (
          <Select allowClear

            showSearch
            placeholder={item.errorMessage}
            // value={item.options}
            onChange={(event, value) => { this.handleSelectChangess(event, value, "community") }}
            optionFilterProp="children"
            filterOption={(input, option: any) => {
              return (Array.isArray(option.props.children) ? option.props.children.join('') : option.props.children).toLowerCase().indexOf(input.toLowerCase()) >= 0
            }}
          >
            {
              item.options.map(element => {
                return <Option value={element.displayName} key={element.companyName}>{element.displayName} 公司:{element.companyName} 部门:{element.department}</Option>
              })
            }
          </Select>
        )
      case 'bianhao':
        return (
          <Input.Group compact>
            <Input allowClear style={{ width: '45%', marginRight: 0, textTransform: 'uppercase' }} placeholder="请输入"
              onChange={(event) => { this.change(event, "contract1") }}
              value={this.state.form.contract1} />
            <Input
              className="site-input-split"
              style={{
                width: '10%',
                background: 'white',
                pointerEvents: 'none',
                border: 'none',
              }}
              allowClear
              placeholder="~"
              disabled
            />
            <Input
              className="site-input-right"
              style={{
                width: ' 45%',
              }}
              allowClear
              placeholder="请输入"
              onChange={(event) => { this.change(event, "contract2") }}
              value={this.state.form.contract2}
            />
          </Input.Group>
        )
      case 'chuangjian':
        return (
          <Input.Group compact>
            <RangePicker allowClear
              style={{ width: '100%' }}
              onChange={this.onChangeRangeDate1}
              format={"YYYY-MM-DD"}
              defaultValue={defaultDateValue}
              placeholder={['选择开始日期', '选择结束日期']}
            />
          </Input.Group>
        )

      case 'mingcheng':
        return (
          <Input.Group compact>
            <Input
              style={{ width: '100%' }}
              placeholder="请输入"
              onChange={(event) => { this.change(event, "contractName") }}
              value={this.state.form.contractName}
              allowClear
            />
          </Input.Group>
        )
      case 'wofang':
        return (
          <Input.Group compact>
            <Input
              style={{ width: '100%' }}
              placeholder="请输入"
              onChange={(event) => { this.change(event, "min") }}
              value={this.state.form.min}
              allowClear

            />
          </Input.Group>
        )
      case 'xiangduifang':
        return (
          <Input.Group compact>
            <Input
              style={{ width: '100%' }}
              placeholder="请输入"
              value={this.state.form.otherSide}
              onChange={(event) => { this.change(event, "otherSide") }}
              allowClear
            />
          </Input.Group>
        )

      case 'multiSelect':
        return (
          <Select allowClear mode='multiple' maxTagCount={1} style={{ width: '100%' }} placeholder={item.errorMessage}>
            {
              item.options.map((option, index) => {
                return (<Option value={option.username} key={option.ID}>{option.username}</Option>)
              })
            }
          </Select>
        )
      default:
        return <Input allowClear />;
    }
  }

  // 法务最后回答日
  fwOnChange1 = (date, dateString) => {
    this.setState({
      form: {
        ...this.state.form,
        dateOf: dateString
      }
    })
  }

  // 下拉框改变赋值
  handleSelectChangess(e, v, key) {
    if (v == undefined) {
      fromData[4].value = undefined
      fromData[6].value = undefined
      fromData[8].value = undefined
      return
    }
    fromData[4].value = v.props.children[0]
    fromData[6].value = v.props.children[2]
    fromData[8].value = v.props.children[4]

    return
    this.setState({
      form: {
        ...this.state.form,
        [key]: e,
        company: v.props.children[2],
        //所属部门
        department: v.props.children[4],
      }
    })
  }


  allowClear(e, key) {
    const { value } = e.target;
    if (!value && e.type !== 'change') {
      // do something
      fromData[18].value = undefined
      fromData[20].value = undefined
      fromData[22].value = undefined
    } else {
      fromData[18].value = e.target.value
    }
  }


  loseFocus(e, key) {
    let array = JSON.parse(sessionStorage.getItem('AADUsers'));
    // 
    let size: any = []
    for (let index = 0; index < array.length; index++) {
      if (e.target.value == array[index].displayName) {
        size.push(array[index])
      }
    }
    // 
    if (size.length == 0) {
      fromData[18].value = e.target.value
      fromData[20].value = undefined
      fromData[22].value = undefined
    } else {
      fromData[18].value = size[0].displayName
      fromData[20].value = size[0].companyName
      fromData[22].value = size[0].department
      this.setState({
        ces: '2'
      })
    }
  }



  // 获取日期
  onChangeRangeDate1 = (value, dateString) => {
    this.setState({
      form: {
        ...this.state.form,
        "dateOf2": dateString[0] ? dateString[0] + ' 00:00:00' : '',
        "dateOf3": dateString[1] ? dateString[1] + ' 23:59:59' : ''
      }
    })

  }

  //时间 转换 时间戳 比较区间
  isMiddle = (aa, bb, cc) => {
    var dateBegin = new Date(aa); //将-转化为/，使用new Date
    var dateEnd = new Date(bb); //将-转化为/，使用new Date
    var dateNow = new Date(cc); //获取当前时间
    var dateBeginNew = dateBegin.getTime();
    var dateEndNew = dateEnd.getTime();
    var dateNowNew = dateNow.getTime();
    let num = dateBeginNew
    let num1 = dateEndNew
    let num2 = dateNowNew
    if (num2 >= num && num2 <= num1) {
      return true
    } else {
      return false
    }
  }


  // 下拉框改变赋值
  handleSelectChange = (e, key) => {
    this.setState({
      form: {
        key: e,
        ...this.state.form,
        [key]: e
      }
    })
  }
  handleSubmit = (e) => {
    if (this.state.checkedList.length == 0) {
      message.warning('请选择搜索范围');
      return
    }
    this.setState({
      loading: true
    })
    localStorage.removeItem('searchForm'); //删除普通检索的条件缓存
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      //
      if (!err) {
        // 清空选中条件
        // let params: CamlParam[] = [];
        // let params: any = [];
        let params: any = [
          {
            logic: "and",
            where: [
              {
                key: 'ContractStatus',
                filterType: "Eq",
                value: "有效"
              }
            ]
          }
        ];



        for (let i = 0; i < fromData.length; i++) {

          let size = fromData[i].field + ""

          // 是否是 有开始时间结束时间
          let istrue = false
          // 是否是审查担当
          let isReview = false


          if (size == "bianhao") {

            // 在两输入框全部输入执行 查流水号区间
            // 在两输入框全部输入执行 查流水号区间
            if (this.state.form.contract1 != null && this.state.form.contract1 != "" && this.state.form.contract2 != null && this.state.form.contract2 != "") {
              // 在输入框1 2 都有值的情况下 判断输入框1值的格式是否正确
              let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;

              let pattern1 = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)(?![A-Za-z]+$)(?=.*-)(?![0-9]+$)[0-9A-Za-z]*(-)?[0-9]*.*\d$/;


              let number1 = this.state.form.contract1
              let number2 = this.state.form.contract2
              //
              // if (this.state.form.contract1.indexOf("-") != -1) {
              //   if (pattern1.test(this.state.form.contract1)) {
              //     // 输入整加版本号查询
              //     // 获取完整加版本号的编号 - 前
              //     let numberBefore = this.getCaption(this.state.form.contract1, 0)
              //     // 获取完整加版本号的编号 - 后
              //     let AfterTheNumber = this.getCaption(this.state.form.contract1, 1)

              //     // 截取编号最后三位流水号
              //     var str1 = numberBefore.substring(numberBefore.length - 7)
              //     // 我方
              //     var our = numberBefore.slice(0, -7)
              //     // 年份
              //     let year = str1.slice(0, 4)
              //     // 流水号
              //     let serialNumber = str1.substring(str1.length - 3)
              //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
              //     //
              //     serialNumber = parseInt(serialNumber)
              //     // 查询条件


              //     // params[0].where.push({
              //     //   key: 'AcceptYear',
              //     //   filterType: "Eq",
              //     //   value: year
              //     // })
              //     // params[0].where.push({
              //     //   key: 'SerialNum',
              //     //   filterType: "Ge",
              //     //   value: serialNumber
              //     // })
              //     // params[0].where.push({
              //     //   key: 'VersionNum',
              //     //   filterType: "Ge",
              //     //   value: AfterTheNumber
              //     // })

              //     number1 = this.state.form.contract1


              //   } else {
              //     message.warning('合同编号格式有误');
              //     this.setState({
              //       loading: false,
              //       inSearchOf: false,
              //     })
              //     return
              //   }
              // } else {
              //   if (pattern.test(this.state.form.contract1)) {
              //     // contract1
              //     // 截取编号最后三位流水号
              //     var str1 = this.state.form.contract1.substring(this.state.form.contract1.length - 7)
              //     // 我方
              //     var our = this.state.form.contract1.slice(0, -7)
              //     // 年份
              //     let year = str1.slice(0, 4)
              //     // 流水号
              //     let serialNumber = str1.substring(str1.length - 3)
              //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
              //     //
              //     serialNumber = parseInt(serialNumber)

              //     // params.push({
              //     //   item1: 'Our',
              //     //   item2: 'AcceptYear',
              //     //   item3: 'SerialNum',
              //     //   text1: our,
              //     //   text2: year,
              //     //   text3: serialNumber,
              //     //   type: "contractNo2"
              //     // })
              //     // params[0].where.push({
              //     //   key: 'Our',
              //     //   filterType: "Eq",
              //     //   value: our
              //     // })
              //     // params[0].where.push({
              //     //   key: 'AcceptYear',
              //     //   filterType: "Eq",
              //     //   value: year
              //     // })
              //     // params[0].where.push({
              //     //   key: 'SerialNum',
              //     //   filterType: "Ge",
              //     //   value: serialNumber
              //     // })

              //     number1 = this.state.form.contract1

              //   } else {
              //     message.warning('合同编号格式有误');
              //     this.setState({
              //       loading: false,
              //       inSearchOf: false,
              //     })
              //     return
              //   }
              // }

              // if (this.state.form.contract2.indexOf("-") != -1) {
              //   if (pattern1.test(this.state.form.contract2)) {
              //     // params.push(new CamlParam("Title", this.state.form.contract2, SPDataType.Text, CAMLCompare.Contains));
              //     // 输入整加版本号查询
              //     // 获取完整加版本号的编号 - 前
              //     let numberBefore = this.getCaption(this.state.form.contract2, 0)
              //     // 获取完整加版本号的编号 - 后
              //     let AfterTheNumber = this.getCaption(this.state.form.contract2, 1)

              //     //
              //     //
              //     // 截取编号最后三位流水号
              //     var str1 = numberBefore.substring(numberBefore.length - 7)
              //     // 我方
              //     var our = numberBefore.slice(0, -7)
              //     // 年份
              //     let year = str1.slice(0, 4)
              //     // 流水号
              //     let serialNumber = str1.substring(str1.length - 3)
              //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
              //     //
              //     serialNumber = parseInt(serialNumber)
              //     // 查询条件
              //     //  我方
              //     // params.push(new CamlParam("Our", our, SPDataType.Text, CAMLCompare.Eq));
              //     // 年份
              //     // params.push(new CamlParam("AcceptYear", year, SPDataType.Number, CAMLCompare.Eq));
              //     // 流水号
              //     // params.push(new CamlParam("SerialNum", serialNumber, SPDataType.Number, CAMLCompare.Leq));//大于等于
              //     //  版本号
              //     // params.push(new CamlParam("VersionNum", AfterTheNumber, SPDataType.Number, CAMLCompare.Leq));//大于等于

              //     // params[0].where.push({
              //     //   key: 'Our',
              //     //   filterType: "Eq",
              //     //   value: our
              //     // })
              //     // params[0].where.push({
              //     //   key: 'AcceptYear',
              //     //   filterType: "Eq",
              //     //   value: year
              //     // })
              //     // params[0].where.push({
              //     //   key: 'SerialNum',
              //     //   filterType: "Ge",
              //     //   value: serialNumber
              //     // })
              //     // params[0].where.push({
              //     //   key: 'VersionNum',
              //     //   filterType: "Ge",
              //     //   value: AfterTheNumber
              //     // })

              //     number2 = this.state.form.contract2

              //   } else {
              //     message.warning('合同编号格式有误');
              //     this.setState({
              //       loading: false,
              //       inSearchOf: false,
              //     })
              //     return
              //   }
              // } else {
              //   // 在输入框1 2 都有值的情况下 判断输入框2值的格式是否正确
              //   if (pattern.test(this.state.form.contract2)) {
              //     // contract2
              //     var str2 = this.state.form.contract2.substring(this.state.form.contract1.length - 7)
              //     let serialNumber2 = str2.substring(str2.length - 3)
              //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
              //     //
              //     serialNumber2 = parseInt(serialNumber2)
              //     // 流水号
              //     // params.push(new CamlParam("SerialNum", serialNumber2, SPDataType.Number, CAMLCompare.Leq));//小于于等于

              //     // params[0].where.push({
              //     //   key: 'SerialNum',
              //     //   filterType: "Le",
              //     //   value: serialNumber2
              //     // })

              //     number2 = this.state.form.contract2


              //   } else {
              //     message.warning('合同编号格式有误');
              //     this.setState({
              //       loading: false,
              //       inSearchOf: false,
              //     })
              //     return
              //   }
              // }
              if (pattern1.test(this.state.form.contract1) && pattern1.test(this.state.form.contract2)) {
                params[0].where.push({
                  key: '',
                  filterType: "ContractNum",
                  value: number1 + "|" + number2
                })
              } else {
                  message.warning('合同编号格式有误');
                  this.setState({
                    loading: false,
                    inSearchOf: false,
                  })
                  return
              }
              



            } else if (this.state.form.contract1 != null && this.state.form.contract1 != "") {
              // 如果不满足两个输入框输入条件 判断输入框1是否有值
              let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;
              // if (pattern.test(this.state.form.contract1)) {
              //   // params.push(new CamlParam("Title", this.state.form.contract1, SPDataType.Text, CAMLCompare.Contains));
              //   // params.push({
              //   //   item: 'Title',
              //   //   text: this.state.form.contract1,
              //   //   type: "indexOf"
              //   // })

              //   // params[0].where.push({
              //   //   key: 'Title',
              //   //   filterType: "Contains",
              //   //   value: this.state.form.contract1
              //   // })
              //   params[0].where.push({
              //     key: '',
              //     filterType: "ContractNum",
              //     value: this.state.form.contract1
              //   })

              // } else {
              //   message.warning('合同编号格式有误');
              //   this.setState({
              //     loading: false,
              //     inSearchOf: false,
              //   })
              //   return
              // }
              if (pattern.test(this.state.form.contract1)) {
                params[0].where.push({
                  key: '',
                  filterType: "ContractNum",
                  value: this.state.form.contract1
                })
              } else {
                message.warning('合同编号格式有误');
                this.setState({
                  loading: false,
                  inSearchOf: false,
                })
                return
              }
              
            } else if (this.state.form.contract2 != null && this.state.form.contract2 != "") {
              // 如果不满足两个输入框输入条件 判断输入框1是否有值
              let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;
              // if (pattern.test(this.state.form.contract2)) {
              //   // params.push(new CamlParam("Title", this.state.form.contract2, SPDataType.Text, CAMLCompare.Contains));
              //   // params.push({
              //   //   item: 'Title',
              //   //   text: this.state.form.contract2,
              //   //   type: "indexOf"
              //   // })

              //   // params[0].where.push({
              //   //   key: 'Title',
              //   //   filterType: "Contains",
              //   //   value: this.state.form.contract2
              //   // })
              //   params[0].where.push({
              //     key: '',
              //     filterType: "ContractNum",
              //     value: this.state.form.contract2
              //   })

              // } else {
              //   message.warning('合同编号格式有误');
              //   this.setState({
              //     loading: false
              //   })
              //   return
              // }
              if (pattern.test(this.state.form.contract2)) {
                params[0].where.push({
                  key: '',
                  filterType: "ContractNum",
                  value: this.state.form.contract2
                })
              } else {
                  message.warning('合同编号格式有误');
                  this.setState({
                    loading: false,
                    inSearchOf: false,
                  })
                  return
              }
              
            }


          } else if (size == "mingcheng") {
            // 合同名称
            if (this.state.form.contractName != null && this.state.form.contractName != "") {
              // this.fuzzy("ContractName", this.state.form.contractName, "Text", "", "")
              // params.push(new CamlParam("ContractName", this.state.form.contractName, SPDataType.Text, CAMLCompare.Contains));
              // params.push({
              //   item: 'ContractName',
              //   text: this.state.form.contractName,
              //   type: "test"
              // })

              params[0].where.push({
                key: 'ContractName',
                filterType: "Contains",
                value: this.state.form.contractName
              })
            }
          } else if (size == "wofang") {
            // 我方
            if (this.state.form.min != null && this.state.form.min != "") {
              // this.fuzzy("Our", this.state.form.min, "Text", "", "")
              // params.push(new CamlParam("Our", this.state.form.min, SPDataType.Text, CAMLCompare.Contains));

              // params.push({
              //   item: 'Our',
              //   text: this.state.form.min,
              //   type: "test"
              // })
              params[0].where.push({
                key: 'Our',
                filterType: "Eq",
                value: this.state.form.min
              })
            }
          } else if (size == "xiangduifang") {
            // 相对方
            if (this.state.form.otherSide != null && this.state.form.otherSide != "") {
              // this.fuzzy("Counterparty", this.state.form.otherSide, "Text", "", "")
              // params.push(new CamlParam("Counterparty", this.state.form.otherSide, SPDataType.Text, CAMLCompare.Contains));
              // params.push({
              //   item: 'Counterparty',
              //   text: this.state.form.otherSide,
              //   type: "indexOf"
              // })

              params[0].where.push({
                key: 'Counterparty',
                filterType: "Contains",
                value: this.state.form.otherSide
              })

            }
          } else if (size == "dandang") {
            // 审查担当
            if ((this.state.form.list != undefined && this.state.form.list != null && this.state.form.list.length != 0) || (this.state.form.personreview != undefined && this.state.form.personreview != null && this.state.form.personreview.length != 0)) {
              let array = []
              // for (let i = 0; i < this.state.form.list.length; i++) {
              //   // params.push(new CamlParam("ReviewOnID", this.state.form.list[i].key, SPDataType.Text, CAMLCompare.Contains));
              //   // array.push(this.state.form.list[i].key)
              //   params[0].where.push({
              //     key: 'ReviewOnID',
              //     filterType: "Contains",
              //     value: this.state.form.list[i].key
              //   })
              // }
              params[0].where.push({
                key: 'ReviewOnID',
                filterType: "MultiUsers",
                value: this.state.form.personreview.map(i => i.replace("-历史", "")).join(';')
              })
              // params.push({
              //   item: 'ReviewOnID',
              //   text: array,
              //   type: "queryId"
              // })

            }
          } else if (size == "chuangjian") {
            if (this.state.form.dateOf2 != "" && this.state.form.dateOf2 != null) {
              // 2022-10-20T00:00:00Z
              let data = this.state.form.dateOf2
              let data1 = this.state.form.dateOf3
              // params.push(new CamlParam("Created", size, SPDataType.DateTime, CAMLCompare.Geq));//我这里用的大于等于，你根据你实际情况来
              // params.push({
              //   item: 'Created',
              //   text: data,
              //   item1: 'Created',
              //   text1: data1,
              //   type: "startEnd"
              // })
              params[0].where.push({
                key: 'Created',
                filterType: "Ge",
                value: data
              })
              params[0].where.push({
                key: 'Created',
                filterType: "Le",
                value: data1
              })
            }

            //结束日期
            // if (this.state.form.dateOf3 != "" && this.state.form.dateOf3 != null) {
            //   let size = this.state.form.dateOf3 + "T00:00:00Z"
            //   params.push(new CamlParam("Created", size, SPDataType.DateTime, CAMLCompare.Leq));//我这里用的小于于等于，你根据你实际情况来
            // }
          } else {

            if (size == "date" && values.date != null && values.date != undefined && values.date != "") {
              values.date = moment(values.date).format('YYYY-MM-DD')
              values.date = values.date
            }

            if (size == "date1" && values.date1 != null && values.date1 != undefined && values.date1 != "") {
              values.date1 = moment(values.date1).format('YYYY-MM-DD')
              values.date1 = values.date1
            }

            // 审查担当
            if (size == "tobear" && values.tobear != null && values.tobear != undefined && values.tobear != "") {
              isReview = true
            }

            if (size == "Legalacceptancedate" && values.Legalacceptancedate != null && values.Legalacceptancedate != undefined && values.Legalacceptancedate != "") {
              values.Legalacceptancedate[0] = moment(values.Legalacceptancedate[0]).format('YYYY-MM-DD')
              values.Legalacceptancedate[0] = values.Legalacceptancedate[0] + "T00:00:00Z"

              values.Legalacceptancedate[1] = moment(values.Legalacceptancedate[1]).format('YYYY-MM-DD')
              values.Legalacceptancedate[1] = values.Legalacceptancedate[1] + "T00:00:00Z"
              istrue = true

            }

            if (values[`${size}`] != null && values[`${size}`] != undefined && values[`${size}`] != "") {
              if (!istrue) {
                // 判断是否是多选框 审查担当
                if (isReview) {
                  // let array = []
                  // for (let i = 0; i < values.tobear.length; i++) {
                  //   array.push(values.tobear[i])
                  // }
                  // params.push({
                  //   item: 'ReviewOnID',
                  //   text: array,
                  //   type: "queryId"
                  // })
                  
                  for (let i = 0; i < values.tobear.length; i++) {
                    // array.push(values.tobear[i])
                    values.tobear[i].replace("-历史", "")
                  }
                  params[0].where.push({
                    key: 'ReviewOnID',
                    filterType: "MultiUsers",
                    value: values.tobear.join(';')
                  })
                } else {
                  // params.push(new CamlParam(fromData[i].header, values[`${size}`], SPDataType[`${fromData[i].theType}`], CAMLCompare[`${fromData[i].conditions}`]));
                  if (size !== 'relyOn') {
                    params[0].where.push({
                      key: fromData[i].header,
                      filterType: fromData[i].conditions,
                      value: values[`${size}`]
                    })
                  }

                }
              } else {
                // params.push(new CamlParam(fromData[i].header, values.Legalacceptancedate[0], SPDataType.DateTime, CAMLCompare.Geq));
                // params.push(new CamlParam(fromData[i].header, values.Legalacceptancedate[1], SPDataType.DateTime, CAMLCompare.Leq));
                // params.push({
                //   item: fromData[i].header,
                //   text: values.Legalacceptancedate[0],
                //   item1: fromData[i].header,
                //   text1: values.Legalacceptancedate[1],
                //   type: "startEnd"
                // })

                params[0].where.push({
                  key: fromData[i].header,
                  filterType: "Ge",
                  value: values.Legalacceptancedate[0]
                })
                params[0].where.push({
                  key: fromData[i].header,
                  filterType: "Le",
                  value: values.Legalacceptancedate[1]
                })


                istrue = false
              }

            }

          }



        }
        this.state.data = []
        let ToTheTotal = []
        // 是否 同时检索 合同 申请书
        // let all = false
        // if (this.state.checkedList.length == 2) {
        //   all = true
        // }

        // if (this.state.checkedList.length != 0) {

        //   let query = ""

        //   for (let i = 0; i < this.state.checkedList.length; i++) {
        //     if (this.state.checkedList[i] == "仅合同") {
        //       // 仅合同
        //       // this.theQuery(params, 1, ToTheTotal)
        //       query += '合同'
        //     }
        //     if (this.state.checkedList[i] == "仅申请书") {

        //       // 仅申请书
        //       // this.theQuery(params, 1, ToTheTotal)
        //       query += '申请书'
        //     }
        //   }

        //   if (query == "合同") {
        //     this.theQuery(params, "合同")
        //   } else if (query == "申请书") {
        //     this.theQuery(params, "申请书")
        //   } else {
        //     this.theQuery(params, "ALL")
        //   }


        // }
        // 检索
        localStorage.setItem('searchFormParams', JSON.stringify(params)); //缓存高级检索item

        fromData[4].value = undefined
        fromData[6].value = undefined
        fromData[8].value = undefined
        this.setParamsByCache(params[0].where); //赋值高级检索弹框params
        // 关闭弹窗
        this.setState({
          visible: false,
          confirmLoading: false,
          filter: params,
          pager: {
            current: 1,
            size: 10
          }
        }, () => {
          this.getData()
        });
      }
    });
  }
  onChange1 = checkedList => {
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && checkedList.length < plainOptions.length,
      checkAll: checkedList.length === plainOptions.length,
    });
  };

  // 获取日期
  onChangeRangeDate = (value, dateString) => {
    this.setState({
      form: {
        ...this.state.form,
        "dateOf": dateString[0] ? dateString[0] + ' 00:00:00' : '',
        "dateOf1": dateString[1] ? dateString[1] + ' 23:59:59' : ''
      }
    })

  }

  // 全选按钮触发
  onCheckAllChange = e => {
    this.setState({
      checkedList: e.target.checked ? plainOptions : [],
      indeterminate: false,
      checkAll: e.target.checked,
    });
  };

  // 高级检索按钮
  advanced = () => {
    if (this.state.checkedList.length == 0) {
      message.warning('请选择搜索范围');
      return
    }
    this.setState({
      visible: true,
    });
  }


  // 检索合同按钮
  retrieve = (text, isBack = 0) => {
    localStorage.removeItem('searchFormParams'); //删除高级检索的条件缓存
    if (this.state.checkedList.length == 0) {
      message.warning('请选择搜索范围');
      return
    }

    if (this.state.inSearchOf) {
      message.warning('检索中');
      return
    }

    // 停止关闭所有定时器
    clearInterval(this.state.time1)
    clearInterval(this.state.time2)
    clearInterval(this.state.time3)
    clearInterval(this.state.time4)
    clearInterval(this.state.time5)
    clearInterval(this.state.time6)
    clearInterval(this.state.time7)
    clearInterval(this.state.time8)

    this.setState({
      loading: true,
      ToTheTotal: [],
      inSearchOf: true,
    })

    // 清空选中条件
    // let params: CamlParam[] = [];
    // let params: any = [];
    // 申请书检索条件
    // let params1: CamlParam[] = [];
    // let params1: any = [];
    let params: any = [
      {
        logic: "and",
        where: [

        ]
      }
    ];

    params[0].where.push({
      key: 'ContractStatus',
      filterType: "Eq",
      value: "有效"
    })

    // 相对方
    if (this.state.form.otherSide != null && this.state.form.otherSide != "") {
      // this.fuzzy("Counterparty", this.state.form.otherSide, "Text", "", "")
      // params.push(new CamlParam("Counterparty", this.state.form.otherSide, SPDataType.Text, CAMLCompare.Contains));
      // params.push({
      //   item: 'Counterparty',
      //   text: this.state.form.otherSide,
      //   type: "indexOf"
      // })


      params[0].where.push({
        key: 'Counterparty',
        filterType: "Contains",
        value: this.state.form.otherSide
      })
    }
    // 合同名称
    if (this.state.form.contractName != null && this.state.form.contractName != "") {
      // this.fuzzy("ContractName", this.state.form.contractName, "Text", "", "")
      // params.push(new CamlParam("ContractName", this.state.form.contractName, SPDataType.Text, CAMLCompare.Contains));
      // params.push({
      //   item: 'ContractName',
      //   text: this.state.form.contractName,
      //   type: "test"
      // })

      params[0].where.push({
        key: 'ContractName',
        filterType: "Contains",
        value: this.state.form.contractName
      })

    }
    //我方
    if (this.state.form.min != null && this.state.form.min != "") {
      // this.fuzzy("Our", this.state.form.min, "Text", "", "")
      // params.push(new CamlParam("Our", this.state.form.min, SPDataType.Text, CAMLCompare.Eq));
      // params.push({
      //   item: 'Our',
      //   text: this.state.form.min,
      //   type: "test"
      // })

      params[0].where.push({
        key: 'Our',
        filterType: "Eq",
        value: this.state.form.min
      })
    }

    // 在两输入框全部输入执行 查流水号区间
    if (this.state.form.contract1 != null && this.state.form.contract1 != "" && this.state.form.contract2 != null && this.state.form.contract2 != "") {
      // 在输入框1 2 都有值的情况下 判断输入框1值的格式是否正确
      let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;

      let pattern1 = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)(?![A-Za-z]+$)(?=.*-)(?![0-9]+$)[0-9A-Za-z]*(-)?[0-9]*.*\d$/;


      let number1 = this.state.form.contract1
      let number2 = this.state.form.contract2


      // if (this.state.form.contract1.indexOf("-") != -1) {
      //   if (pattern1.test(this.state.form.contract1)) {
      //     // 输入整加版本号查询
      //     // 获取完整加版本号的编号 - 前
      //     let numberBefore = this.getCaption(this.state.form.contract1, 0)
      //     // 获取完整加版本号的编号 - 后
      //     let AfterTheNumber = this.getCaption(this.state.form.contract1, 1)

      //     // 截取编号最后三位流水号
      //     var str1 = numberBefore.substring(numberBefore.length - 7)
      //     // 我方
      //     var our = numberBefore.slice(0, -7)
      //     // 年份
      //     let year = str1.slice(0, 4)
      //     // 流水号
      //     let serialNumber = str1.substring(str1.length - 3)
      //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
      //     //
      //     serialNumber = parseInt(serialNumber)
      //     // 查询条件


      //     // params[0].where.push({
      //     //   key: 'AcceptYear',
      //     //   filterType: "Eq",
      //     //   value: year
      //     // })
      //     // params[0].where.push({
      //     //   key: 'SerialNum',
      //     //   filterType: "Ge",
      //     //   value: serialNumber
      //     // })
      //     // params[0].where.push({
      //     //   key: 'VersionNum',
      //     //   filterType: "Ge",
      //     //   value: AfterTheNumber
      //     // })

      //     number1 = this.state.form.contract1


      //   } else {
      //     message.warning('合同编号格式有误');
      //     this.setState({
      //       loading: false,
      //       inSearchOf: false,
      //     })
      //     return
      //   }
      // } else {
      //   if (pattern.test(this.state.form.contract1)) {
      //     // contract1
      //     // 截取编号最后三位流水号
      //     var str1 = this.state.form.contract1.substring(this.state.form.contract1.length - 7)
      //     // 我方
      //     var our = this.state.form.contract1.slice(0, -7)
      //     // 年份
      //     let year = str1.slice(0, 4)
      //     // 流水号
      //     let serialNumber = str1.substring(str1.length - 3)
      //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
      //     //
      //     serialNumber = parseInt(serialNumber)

      //     // params.push({
      //     //   item1: 'Our',
      //     //   item2: 'AcceptYear',
      //     //   item3: 'SerialNum',
      //     //   text1: our,
      //     //   text2: year,
      //     //   text3: serialNumber,
      //     //   type: "contractNo2"
      //     // })
      //     // params[0].where.push({
      //     //   key: 'Our',
      //     //   filterType: "Eq",
      //     //   value: our
      //     // })
      //     // params[0].where.push({
      //     //   key: 'AcceptYear',
      //     //   filterType: "Eq",
      //     //   value: year
      //     // })
      //     // params[0].where.push({
      //     //   key: 'SerialNum',
      //     //   filterType: "Ge",
      //     //   value: serialNumber
      //     // })

      //     number1 = this.state.form.contract1

      //   } else {
      //     message.warning('合同编号格式有误');
      //     this.setState({
      //       loading: false,
      //       inSearchOf: false,
      //     })
      //     return
      //   }
      // }

      // if (this.state.form.contract2.indexOf("-") != -1) {
      //   if (pattern1.test(this.state.form.contract2)) {
      //     // params.push(new CamlParam("Title", this.state.form.contract2, SPDataType.Text, CAMLCompare.Contains));
      //     // 输入整加版本号查询
      //     // 获取完整加版本号的编号 - 前
      //     let numberBefore = this.getCaption(this.state.form.contract2, 0)
      //     // 获取完整加版本号的编号 - 后
      //     let AfterTheNumber = this.getCaption(this.state.form.contract2, 1)

      //     //
      //     //
      //     // 截取编号最后三位流水号
      //     var str1 = numberBefore.substring(numberBefore.length - 7)
      //     // 我方
      //     var our = numberBefore.slice(0, -7)
      //     // 年份
      //     let year = str1.slice(0, 4)
      //     // 流水号
      //     let serialNumber = str1.substring(str1.length - 3)
      //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
      //     //
      //     serialNumber = parseInt(serialNumber)
      //     // 查询条件
      //     //  我方
      //     // params.push(new CamlParam("Our", our, SPDataType.Text, CAMLCompare.Eq));
      //     // 年份
      //     // params.push(new CamlParam("AcceptYear", year, SPDataType.Number, CAMLCompare.Eq));
      //     // 流水号
      //     // params.push(new CamlParam("SerialNum", serialNumber, SPDataType.Number, CAMLCompare.Leq));//大于等于
      //     //  版本号
      //     // params.push(new CamlParam("VersionNum", AfterTheNumber, SPDataType.Number, CAMLCompare.Leq));//大于等于

      //     // params[0].where.push({
      //     //   key: 'Our',
      //     //   filterType: "Eq",
      //     //   value: our
      //     // })
      //     // params[0].where.push({
      //     //   key: 'AcceptYear',
      //     //   filterType: "Eq",
      //     //   value: year
      //     // })
      //     // params[0].where.push({
      //     //   key: 'SerialNum',
      //     //   filterType: "Ge",
      //     //   value: serialNumber
      //     // })
      //     // params[0].where.push({
      //     //   key: 'VersionNum',
      //     //   filterType: "Ge",
      //     //   value: AfterTheNumber
      //     // })

      //     number2 = this.state.form.contract2

      //   } else {
      //     message.warning('合同编号格式有误');
      //     this.setState({
      //       loading: false,
      //       inSearchOf: false,
      //     })
      //     return
      //   }
      // } else {
      //   // 在输入框1 2 都有值的情况下 判断输入框2值的格式是否正确
      //   if (pattern.test(this.state.form.contract2)) {
      //     // contract2
      //     var str2 = this.state.form.contract2.substring(this.state.form.contract1.length - 7)
      //     let serialNumber2 = str2.substring(str2.length - 3)
      //     // 库里面的流水号是 003 004这种 直接转换数字类似去掉00
      //     //
      //     serialNumber2 = parseInt(serialNumber2)
      //     // 流水号
      //     // params.push(new CamlParam("SerialNum", serialNumber2, SPDataType.Number, CAMLCompare.Leq));//小于于等于

      //     // params[0].where.push({
      //     //   key: 'SerialNum',
      //     //   filterType: "Le",
      //     //   value: serialNumber2
      //     // })

      //     number2 = this.state.form.contract2


      //   } else {
      //     message.warning('合同编号格式有误');
      //     this.setState({
      //       loading: false,
      //       inSearchOf: false,
      //     })
      //     return
      //   }
      // }
      if (pattern1.test(this.state.form.contract1) && pattern1.test(this.state.form.contract2)) {
        params[0].where.push({
          key: '',
          filterType: "ContractNum",
          value: number1 + "|" + number2
        })
      } else {
          message.warning('合同编号格式有误');
          this.setState({
            loading: false,
            inSearchOf: false,
          })
          return
      }
      



    } else if (this.state.form.contract1 != null && this.state.form.contract1 != "") {
      // 如果不满足两个输入框输入条件 判断输入框1是否有值
      let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;
      // if (pattern.test(this.state.form.contract1)) {
      //   // params.push(new CamlParam("Title", this.state.form.contract1, SPDataType.Text, CAMLCompare.Contains));
      //   // params.push({
      //   //   item: 'Title',
      //   //   text: this.state.form.contract1,
      //   //   type: "indexOf"
      //   // })

      //   // params[0].where.push({
      //   //   key: 'Title',
      //   //   filterType: "Contains",
      //   //   value: this.state.form.contract1
      //   // })
      //   params[0].where.push({
      //     key: '',
      //     filterType: "ContractNum",
      //     value: this.state.form.contract1
      //   })

      // } else {
      //   message.warning('合同编号格式有误');
      //   this.setState({
      //     loading: false,
      //     inSearchOf: false,
      //   })
      //   return
      // }
      if (pattern.test(this.state.form.contract1)) {
        params[0].where.push({
          key: '',
          filterType: "ContractNum",
          value: this.state.form.contract1
        })
      } else {
        message.warning('合同编号格式有误');
        this.setState({
          loading: false,
          inSearchOf: false,
        })
        return
      }
      
    } else if (this.state.form.contract2 != null && this.state.form.contract2 != "") {
      // 如果不满足两个输入框输入条件 判断输入框1是否有值
      let pattern = /^[A-Za-z]{1}(?![0-9]+$)(?![A-Za-z]+$)[0-9A-Za-z]*(-)?[0-9]*$/;
      // if (pattern.test(this.state.form.contract2)) {
      //   // params.push(new CamlParam("Title", this.state.form.contract2, SPDataType.Text, CAMLCompare.Contains));
      //   // params.push({
      //   //   item: 'Title',
      //   //   text: this.state.form.contract2,
      //   //   type: "indexOf"
      //   // })

      //   // params[0].where.push({
      //   //   key: 'Title',
      //   //   filterType: "Contains",
      //   //   value: this.state.form.contract2
      //   // })
      //   params[0].where.push({
      //     key: '',
      //     filterType: "ContractNum",
      //     value: this.state.form.contract2
      //   })

      // } else {
      //   message.warning('合同编号格式有误');
      //   this.setState({
      //     loading: false
      //   })
      //   return
      // }
      if (pattern.test(this.state.form.contract2)) {
        params[0].where.push({
          key: '',
          filterType: "ContractNum",
          value: this.state.form.contract2
        })
      } else {
        message.warning('合同编号格式有误');
        this.setState({
          loading: false,
          inSearchOf: false,
        })
        return
      }
      
    }

    //
    // 法务受理日
    if (this.state.form.dateOf != "" && this.state.form.dateOf != null) {
      //
      // 2022-10-20T00:00:00Z
      let size = this.state.form.dateOf
      // params.push(new CamlParam("AcceptTime", size, SPDataType.DateTime, CAMLCompare.Eq));//我这里用的大于等于，你根据你实际情况来
      // params.push({
      //   item: 'AcceptTime',
      //   text: size,
      //   type: "indexOf"
      // })
      params[0].where.push({
        key: 'AcceptTime',
        filterType: "Ge",
        value: size
      })

    }
    if ((this.state.form.list != undefined && this.state.form.list != null && this.state.form.list.length != 0) || (this.state.form.personreview != undefined && this.state.form.personreview != null && this.state.form.personreview.length != 0)) {
      // this.fuzzy("ReviewOnID", this.state.form.personreview, "Number", "", "")
      // for (let i = 0; i < this.state.form.list.length; i++) {
      //   params.push(new CamlParam("ReviewOnID", this.state.form.list[i].key, SPDataType.Text, CAMLCompare.Contains));

      // }
      // let array = []
      // 
      // for (let i = 0; i < this.state.form.list.length; i++) {
      //   // array.push(this.state.form.list[i].key)
      //   params[0].where.push({
      //     key: 'ReviewOnID',
      //     filterType: "Contains",
      //     value: this.state.form.list[i].props.value.replace("-历史", "")

      //   })
      // }
      params[0].where.push({
        key: 'ReviewOnID',
        filterType: "MultiUsers",
        value: this.state.form.personreview.map(i => i.replace("-历史", "")).join(';')
      })
      // params.push({
      //   item: 'ReviewOnID',
      //   text: array,
      //   type: "queryId"
      // })
      // params.push(new CamlParam("ReviewOnID", this.state.form.personreview, SPDataType.Number, CAMLCompare.Eq));
    }

    //结束日期
    // if (this.state.form.dateOf1 != "" && this.state.form.dateOf1 != null) {
    //   let size = this.state.form.dateOf1 + "T00:00:00Z"
    //   params.push(new CamlParam("AcceptTime", size, SPDataType.DateTime, CAMLCompare.Leq));//我这里用的小于于等于，你根据你实际情况来
    // }

    // params1.push(new CamlParam("ItemBelong", '0', SPDataType.Number, CAMLCompare.Eq));//查询合同申请书
    // params1.push({
    //   item: 'ItemBelong',
    //   text: 0,
    //   type: "test"
    // })
    // this.state.ToTheTotal = []


    let ToTheTotal = []
    this.state.data = []
    //
    // 是否 同时检索 合同 申请书
    // let all = false
    // if (this.state.checkedList.length == 2) {
    //   all = true
    // }

    // if (this.state.checkedList.length != 0) {

    //   let query = ""

    //   for (let i = 0; i < this.state.checkedList.length; i++) {
    //     if (this.state.checkedList[i] == "仅合同") {
    //       query += '合同'
    //     }
    //     if (this.state.checkedList[i] == "仅申请书") {
    //       query += '申请书'
    //     }
    //   }

    //   if (query == "合同") {
    //     this.theQuery(params, "合同")
    //   } else if (query == "申请书") {
    //     this.theQuery(params, "申请书")
    //   } else {
    //     this.theQuery(params, "ALL")
    //   }


    // }

    let form = this.state.form;
    
    
    localStorage.setItem('checkedList', JSON.stringify(this.state.checkedList))
    localStorage.setItem('checkAll', JSON.stringify(this.state.checkAll))
    localStorage.setItem('indeterminate', JSON.stringify(this.state.indeterminate))
    if (form.personreview == undefined) {
      localStorage.setItem('searchForm', JSON.stringify(form));
    }else{
      // localStorage.setItem('searchFormList', JSON.stringify(form.list));
      form.list = [];
      localStorage.setItem('searchForm', JSON.stringify(form));
    }

    this.theQuery(params, isBack)
  }
  // 下拉框改变赋值
  handleSelectChanges(e, v, key) {
    var array = []
    var arrays = []
    v.forEach(element => {
      array.push(element.key)
      arrays.push(`${element.props.value}#${element.props.children}`)
    });
    this.setState({
      form: {
        ...this.state.form,
        reviewOn: array.join(","),
        reviewOnxuans: arrays.join(';'),
        [key]: e,
        "list": v,
      }
    })
  }
  getCaption = (obj, state) => {
    var index = obj.lastIndexOf("\-");
    if (state == 0) {
      obj = obj.substring(0, index);
    } else {
      obj = obj.substring(index + 1, obj.length);
    }
    return obj;
  }
  onChange = (e, key) => {
    this.setState({
      form: {
        ...this.state.form,
        [key]: e
      }
    })
  }

  //弹框取消
  handleCancel = () => {
    fromData[4].value = undefined
    fromData[6].value = undefined
    fromData[8].value = undefined
    this.setState({
      visible: false,
    });
  };

  // 输入框改变赋值
  change(e, key) {
    this.setState({
      form: {
        ...this.state.form,
        [key]: e.target.value
      }
    })
  }

  public render(): React.ReactElement {
    const { getFieldDecorator } = this.props.form;
    const { visible, confirmLoading } = this.state;
    return (
      <div className='box'>
        <Spin  spinning={this.state.loading}>
        <div className="box_content">
          <div className="box_top">

            <Row type="flex" justify="end">
              {
                isHavePermission('SearchContract/moresearch') ? <Col><Button type="primary" className="Button_1" onClick={this.advanced} >高级检索</Button></Col> : null
              }
              {
                isHavePermission('SearchContract/search') ? <Col><Button type="primary" onClick={this.retrieve}>检索</Button></Col> : null
              }
            </Row>

            <div className="placeholder"></div>

            <Row type="flex" align="middle" justify="space-between">

              <Col span={7}>
                <Form.Item label="合同编号" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  <Input.Group compact>
                    <Input allowClear style={{ width: '45%', marginRight: 0, textTransform: 'uppercase' }} placeholder="请输入"
                      onChange={(event) => { this.change(event, "contract1") }} value={this.state.form.contract1}/>
                    <Input
                      className="site-input-split"
                      style={{
                        width: '10%',
                        background: 'white',
                        pointerEvents: 'none',
                        border: 'none',
                      }}
                      allowClear
                      placeholder="~"
                      disabled
                    />
                    <div></div>
                    <Input
                      className="site-input-right"
                      style={{
                        width: ' 45%',
                      }}
                      allowClear
                      placeholder="请输入"
                      onChange={(event) => { this.change(event, "contract2") }}
                      value={this.state.form.contract2}
                    />
                  </Input.Group>
                </Form.Item>


              </Col>
              <Col span={7}>

                {/* <Form.Item label="法务受理日">
                  <RangePicker allowClear 
                    style={{ width: '100%' }}
                    defaultValue={[moment('2015/01/01', dateFormat), moment('2015/01/01', dateFormat)]}
                    format={dateFormat}
                  />
                </Form.Item> */}
                <Form.Item label="法务受理日" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  {/* <RangePicker allowClear 
                    onChange={this.onChangeRangeDate}
                    placeholder={['选择开始日期', '选择结束日期']}
                    style={{ width: '100%' }}
                    format={"YYYY-MM-DD"}
                  /> */}
                  {/* <DatePicker allowClear  format={dateFormat} style={{ width: '100%' }} placeholder={"请选择日期"} />; */}
                  <DatePicker allowClear style={{ width: '100%' }} placeholder="请选择年份" onChange={this.fwOnChange1} format={"YYYY-MM-DD"} />
                </Form.Item>
              </Col>
              <Col span={7}>

                <Form.Item label="合同名称" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  <Input
                    className="site-input-right"
                    style={{
                      width: '100%',
                    }}
                    allowClear
                    placeholder="请输入"
                    value={this.state.form.contractName} 
                    onChange={(event) => { this.change(event, "contractName") }}
                  />
                </Form.Item>

              </Col>

              <Col span={7} >
                <Form.Item label="我方" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left" >
                  <Select allowClear
                    style={{
                      width: '100%',
                    }}
                    onChange={(event) => { this.handleSelectChange(event, "min") }}
                    placeholder="请选择"
                    value={this.state.form.min}
                  >
                    {
                      this.state.weList.map(element => {
                        return <Option value={element} key={element}>{element}</Option>
                      })
                    }
                  </Select>
                  {/* <Input
                    className="site-input-right"
                    style={{
                      width: '100%',
                    }}
                    placeholder="请输入"
                    onChange={(event) => { this.change(event, "min") }}
                    value={this.state.form.min}

                  /> */}
                </Form.Item>

              </Col>

              <Col span={7}>

                <Form.Item label="相对方" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  <Input
                    className="site-input-right"
                    style={{
                      width: '100%',
                    }}
                    allowClear
                    placeholder="请输入"
                    value={this.state.form.otherSide}
                    onChange={(event) => { this.change(event, "otherSide") }}
                  />
                </Form.Item>

              </Col>
              <Col span={7}>
                <Form.Item label='审查担当' labelAlign="left" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                  <Select allowClear mode='multiple' placeholder="请选择" style={{ width: '100%' }} value={this.state.form.personreview}
                    onChange={(event, value) => { this.handleSelectChanges(event, value, "personreview") }} maxTagCount={2}>
                    {
                      this.state.personreviewList.map(element => {
                        return <Option value={element.username} key={element.ID}>{element.username}</Option>
                      })
                    }
                  </Select>
                </Form.Item>

              </Col>
              <Col span={7}></Col>
            </Row>

            <Row type="flex" align="middle">
              <Col span={7}>
                <Form.Item label='搜索范围' labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
                  <CheckboxGroup
                    options={plainOptions}
                    value={this.state.checkedList}
                    onChange={this.onChange1}
                  />
                  <Checkbox
                    indeterminate={this.state.indeterminate}
                    onChange={this.onCheckAllChange}
                    checked={this.state.checkAll}
                  >
                    全部
                  </Checkbox>
                </Form.Item>
              </Col>
            </Row>

          </div>
          <div style={{ height: '24px' }}></div>
          <div className="box_toble">
            <ConfigProvider locale={this.state.local}>
              <Table columns={columns} dataSource={this.state.data}
                rowKey={record => record.id}
                pagination={{
                  // onChange: this.ontab.bind(this),
                  hideOnSinglePage: false,
                  total: this.state.totalnum,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  defaultCurrent: 1,
                  current: this.state.pager.current,
                  pageSize: this.state.pager.size,
                  onChange: (page, pageSize?) => {
                    this.setState({
                      pager: {
                        current: page,
                        size: pageSize
                      }
                    }, () => {
                      this.getData()
                    })
                  },
                  onShowSizeChange: (page, pageSize?) => {
                    this.setState({
                      pager: {
                        current: page,
                        size: pageSize
                      }
                    }, () => this.getData())
                  },
                  showTotal: function (total) {
                    return `总共有 ${total} 条数据`;
                  }
                }} />
            </ConfigProvider>
          </div>
          <Modal
            destroyOnClose={true}
            visible={visible}
            onCancel={this.handleCancel}
            closable={false}
            footer={null}
            width={'63%'}
          >
            <Form onSubmit={this.handleSubmit} layout='inline' >
              <Row>
                {
                  fromData.map((item, index) => {
                    // type 为 date 日期格式需要强制转化为 moment 格式
                    item.value = item.type == 'date' ? item.value == null ? null : moment(item.value, 'YYYY-MM-DD') : item.value;
                    // item.value = item.type == 'date' ? moment(item.value, 'YYYY-MM-DD') : item.value;
                    return (
                      <Col span={11} offset={index % 2 == 0 ? 0 : 2}>
                        <Form.Item
                          key={index}
                          {...formItemLayout}
                          label={item.text}
                          style={{ display: 'flex', marginTop: '15px' }}
                        >
                          {getFieldDecorator(item.field, {
                            initialValue: item.value,
                            rules: [{
                              required: item.required,
                              message: item.errorMessage
                            }],
                          })(
                            this.switchItem(item)
                          )}
                        </Form.Item>
                      </Col>

                    )
                  })
                }
              </Row>
              <Row>
                <Col span={3} offset={9}>
                  <Form.Item>
                    <Button type="primary" style={{ padding: ' 0 24px' }} onClick={this.handleSubmit}>检索</Button>
                  </Form.Item>
                </Col>
                <Col span={3}>
                  <Form.Item>
                    <Button type="primary" style={{ padding: ' 0 24px' }} onClick={this.handleCancel}>取消</Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Modal>
        </div>
        </Spin>
        
      </div>
    );
  }
  async getData() {
    this.setState({
      loading: true
    })
    localStorage.setItem('PageIndex', JSON.stringify(this.state.pager.current)); //设置页码
    
    // 合同表
    let updateList = {
      Total: 0,
      data: []
    };
    let filter = JSON.parse(JSON.stringify(this.state.filter));

    if(filter[0].where.length == 0){
      filter[0].where = [
        {
          key: 'ContractStatus',
          filterType: "Eq",
          value: "有效"
        }
      ]
    }

    // 
    
    let newFilter = [];
    let rooterGuid = [];

    let relyOn: any = await this.props.form.validateFields(['relyOn'])
    // let relyonArr = [];
    // if (relyOn.relyOn) {
    //   relyonArr = [{
    //     key: 'RelierName',
    //     filterType: "Eq",
    //     value: relyOn.relyOn
    //   }, {
    //     key: 'apply_user_nm',
    //     filterType: "Eq",
    //     value: relyOn.relyOn
    //   }]
    // }
    // 
    // 
    if (this.state.checkedList.indexOf('仅合同') !== -1 && this.state.checkedList.indexOf('仅申请书') !== -1) {
      rooterGuid = [ListGUID.StandingBook, ListGUID.Petition, 'PetitionBindContract'];
      newFilter.push({
        logic: "and",
        ListGuid: ListGUID.StandingBook,
        where: relyOn.relyOn && relyOn.relyOn !== undefined ? [...filter[0].where, ...[{
          key: 'RelierName',
          filterType: "Eq",
          value: relyOn.relyOn
        }]] : filter[0].where
      },
        {
          logic: "and",
          ListGuid: 'PetitionBindContract',
          where: relyOn.relyOn && relyOn.relyOn !== undefined ? [...filter[0].where, ...[{
            key: 'apply_user_nm',
            filterType: "Eq",
            value: relyOn.relyOn
          }, {
            key: 'ItemBelong',
            filterType: "Eq",
            value: '0'
          }]] : [...filter[0].where, ...[{
            key: 'ItemBelong',
            filterType: "Eq",
            value: '0'
          }]]
        })
    } else {
      if (this.state.checkedList.indexOf('仅合同') !== -1) {
        rooterGuid.push(ListGUID.StandingBook)
        newFilter.push({
          logic: "and",
          ListGuid: ListGUID.StandingBook,
          where: relyOn.relyOn ? [...filter[0].where, ...[{
            key: 'RelierName',
            filterType: "Eq",
            value: relyOn.relyOn
          }]] : filter[0].where
        })
      }
      if (this.state.checkedList.indexOf('仅申请书') !== -1) {
        rooterGuid = ['PetitionBindContract', ListGUID.Petition]
        newFilter.push({
          logic: "and",
          ListGuid: ListGUID.Petition,
          where: relyOn.relyOn ? [...filter[0].where, ...[{
            key: 'apply_user_nm',
            filterType: "Eq",
            value: relyOn.relyOn
          }, {
            key: 'ItemBelong',
            filterType: "Eq",
            value: '0'
          }]] : [...filter[0].where, ...[{
            key: 'ItemBelong',
            filterType: "Eq",
            value: '0'
          }]]
        })
      }
    }

    let data = await Api._getPaged({ Guid: rooterGuid, PageSize: this.state.pager.size, PageIndex: this.state.pager.current, FilterL: newFilter })
    if(data.data){
      updateList.data = updateList.data.concat(data.data)
      updateList.Total = data.Total
      // if(this.state.checkedList.indexOf('仅合同') !== -1) {
      //   
      //   let data = await Api._getPaged({ Guid: ListGUID.StandingBook, PageSize: this.state.pager.size, PageIndex: this.state.pager.current, FilterL: []})
      //   updateList.data.concat(data.data)
      //   updateList.Total += data.Total
      // }
      // 
      // if(this.state.checkedList.indexOf('仅申请书') !== -1) {
      //   
      //   let filter = JSON.parse(JSON.stringify(this.state.filter))
      //   if(filter[0].where.length !== 0) {
      //     filter[0].where.push({
      //       key: 'ItemBelong',
      //       filterType: "Eq",
      //       value: '0'
      //     })
      //   } else {
      //     filter[0].where = [
      //       {
      //         key: 'ItemBelong',
      //         filterType: "Eq",
      //         value: '0'
      //       }
      //     ]
      //   }
      //   let data = await Api._getPaged({ Guid: ListGUID.Petition, PageSize: this.state.pager.size, PageIndex: this.state.pager.current, FilterL: filter })
      //   updateList.data.concat(data.data)
      //   updateList.Total += data.Total
      // }
      
      // 申请书表
      // let updateList1 = await Api._getPaged({Guid: ListGUID.Petition, PageSize: this.state.pager.size,PageIndex: this.state.pager.current, FilterL: this.state.filter });
      for (let i = 0; i < updateList.data.length; i++) {
        if (updateList.data[i].FileAddress) {
          // 
          let file = await Api.getFiles(ListGUID.ContractLibRelativeUrl + '/' + updateList.data[i].FileAddress);

          // 处理时间排序
          file.sort(function (a, b) {
            return b.TimeCreated < a.TimeCreated ? -1 : 1
          })
          updateList.data[i].file = file
        } else if (updateList.data[i].SRUrls) {
          let index = updateList.data[i].SRUrls.indexOf("/")
          updateList.data[i].SRUrls = updateList.data[i].SRUrls.substring(index);
          let file = await Api.getFiles(ListGUID.ContractPetitionLibRelativeUrl + '/' + updateList.data[i].SRUrls + '/');
          file.sort(function (a, b) {
            return b.TimeCreated < a.TimeCreated ? -1 : 1
          })
          updateList.data[i].file = file
        } else {
          updateList.data[i].file = []
        }
      }

      this.setState({
        // allData: updateList2,
        // allData1: updateList1,
        data: updateList.data,
        // totalnum: updateList.length,
        totalnum: updateList.Total,
        loading: false,
        inSearchOf: false
      })
    } else {
      this.setState({
        loading: false,
        inSearchOf: false
      })
    }
    
  }
  //合同性质 合同期限 合同重要性 律师审查 审查担当  公司设置  问题 部门列表
  public async getTest() {
    // 公司设置
    // let Companysettings = await Api._getModel({ Guid: ListGUID.Companies });
    let Companysettings = JSON.parse(sessionStorage.getItem('userDataPer')).ContractWindowCompany && JSON.parse(sessionStorage.getItem('userDataPer')).ContractWindowCompany.length > 0 ? JSON.parse(sessionStorage.getItem('userDataPer')).ContractWindowCompany : JSON.parse(sessionStorage.getItem('userDataPer')).PermissionCompany
    // let userRoleName = JSON.parse(sessionStorage.getItem('userRoleName'))
   
    // if(userRoleName) {
    //   let roleArr = userRoleName.split(',');
    //   let arr = Companysettings.filter(i => roleArr.includes(i.Title))
    //   Companysettings = arr.length > 0 ? arr : Companysettings
    // }
    // 单选赋值
    this.state.checkedList = plainOptions
    
    // 全选状态
    this.state.checkAll = true

    // // 仅合同表
    // var param = {
    //   Guid: ListGUID.StandingBook, //表数据
    //   PageSize: this.state.pager.size,PageIndex: this.state.pager.current
    // };
    // // 表格loading打开
    // // this.loading = true
    // let Naturcontract = await Api._getPaged(param);
    // let updateList = await Api._getPermissionData(ListGUID.StandingBook, Naturcontract)
    // //

    // // 仅申请书表
    // var param1 = {
    //   Guid: ListGUID.Petition, //表数据
    //   PageSize: this.state.pager.size,PageIndex: this.state.pager.current
    //   // Filter: `ItemBelong eq '0'`
    // };
    // // this.loading = true
    // // let Naturcontract1 = await Api._getPaged(param1);

    // // let Naturcontract2 = []
    // // Naturcontract1.forEach(element => {
    // //   if (element.ItemBelong == 0) {
    // //     Naturcontract2.push(element)
    // //   }
    // // });
    // let updateList1 = await Api._getPaged(param1)
    // // let updateList1 = await Api._getPermissionData(ListGUID.Petition, Naturcontract2)

    // this.state.time8 = setTimeout(() => {
    //   //
    // }, 200)




    //审查担当
    let Person = await Api._getModel({ Guid: ListGUID.ReviewOn });
    const userList = JSON.parse(localStorage.getItem('usersList'));
    Person.forEach(async item => {
      item.username = item.Title
      // let informationid = await Api.GetUserById(item.ReviewUserId)
      let informationid = userList.filter(i => i.id === item.ReviewUserId)
      if (informationid && informationid.length > 0) {
        item.Title = informationid.Title
      }

      return
    });
    let historyReviewOn = Person.filter(i => i.Title.includes('-历史'));
    let nowReviewOn = Person.filter(i => !i.Title.includes('-历史'))
    Person = [...nowReviewOn, ...historyReviewOn];
    fromData[23].options = Person
    fromData[14].options = Companysettings

    // 高级检索
    // 问题
    let Problem = await Api._getModel({ Guid: ListGUID.Question, });
    // Problem
    fromData[3].options = Problem

    //合同性质
    let theNature = await Api._getModel({ Guid: ListGUID.ContractNature });
    fromData[5].options = theNature


    // 合同期限
    let timeLimit = await Api._getModel({ Guid: ListGUID.ContractPeriod });
    fromData[7].options = timeLimit


    //合同重要性
    let Contractimportance = await Api._getModel({ Guid: ListGUID.ContractImportance });
    fromData[9].options = Contractimportance

    //律师审查
    let Lawyerreview = await Api._getModel({ Guid: ListGUID.LawerReview, });
    fromData[17].options = Lawyerreview

    // 合同修改性质
    let modifyThe = await Api._getModel({ Guid: ListGUID.ContractReviseNature });

    // 资质
    fromData[13].options = [{ ID: "有", Title: "有" }, { ID: "无", Title: "无" }, { ID: "无需资质", Title: "无需资质" }]


    this.setState({
      personreviewList: Person,
      inSearchOf: false,
      weList: Companysettings,
    })
  }


  public async theQuery(params, isBack = 0) {
    if (isBack == 0) {
      this.setState({
        filter: params || [],
        // 检索的时候 是新list 需要把页码重置
        pager: {
          current: 1,
          size: 10
        }
      }, () => {
        this.getData()
      })
    }else{
      this.setState({
        filter: params || [],
        //从详情页返回不重置页码 
      }, () => {
        this.getData()
      })
    }
    // 检索结果的list
    let screenList = []
  }



  // public async theQuery1(params, index, ToTheTotal) {
  //   return
  //   var param = params
  //   if (index == 2) {
  //     //
  //     let camlQuery = {
  //       ViewXml: ''
  //     }

  //     //不排序
  //     let demo = Api.buildCamlXml(params);

  //     let Guid = ListGUID.StandingBook //根据条件检索表数据

  //     camlQuery.ViewXml = demo

  //     let Naturcontract1 = await Api.GetListItemsByCAMLQuery(Guid, camlQuery);
  //     //
  //     var array = []
  //     Naturcontract1.forEach(async element => {
  //       // 仅申请书表
  //       var param1 = {
  //         Guid: ListGUID.Petition, //表数据
  //         Filter: `ItemBelong eq '0' and Title eq '${element.Title}'`
  //       };
  //       let filterlist = await Api._getModel(param1);
  //       if (filterlist.length != 0) {
  //         array.push(filterlist[0])
  //       }
  //     });
  //     this.state.time5 = setTimeout(async () => {
  //       var updateList = await Api._getPermissionData(ListGUID.Petition, array)
  //       updateList.forEach(async element => {
  //         element.ContractName = element.filename
  //         element.Counterparty = element.company_name
  //         if (element.SRUrls != null) {
  //           let index = element.SRUrls.lastIndexOf("/")
  //           element.SRUrls = element.SRUrls.substring(0, index);
  //           //
  //           let file = await Api.getFiles(element.SRUrls);
  //           element.file = file
  //         } else {
  //           let file = []
  //           element.file = file
  //         }
  //       });
  //       ToTheTotal = this.state.data.concat(updateList)
  //       //
  //       let arr = ToTheTotal
  //       //
  //       this.setState({
  //         data: arr,
  //         totalnum: arr.length,
  //         loading: false,
  //         inSearchOf: false
  //       })
  //     }, 300)
  //     this.state.time4 = setTimeout(async () => {
  //       //

  //     }, 1000)
  //   } else {
  //     if (this.state.form.personreview != undefined && this.state.form.personreview != "" || this.state.form.min != undefined && this.state.form.min != "" || this.state.form.otherSide != null && this.state.form.otherSide != "" || this.state.form.contract1 != null && this.state.form.contract1 != "" || this.state.form.contract2 != null && this.state.form.contract2 != ""
  //       || this.state.form.contractName != null && this.state.form.contractName != "" || this.state.form.dateOf1 != "" && this.state.form.dateOf1 != null || this.state.form.dateOf != "" && this.state.form.dateOf != null || this.state.form.list != undefined && this.state.form.list != null && this.state.form.list.length != 0
  //     ) {
  //       let camlQuery = {
  //         ViewXml: ''
  //       }

  //       //不排序
  //       let demo = Api.buildCamlXml(params);
  //       //

  //       let Guid = ListGUID.StandingBook //根据条件检索表数据

  //       camlQuery.ViewXml = demo

  //       let Naturcontract1 = await Api.GetListItemsByCAMLQuery(Guid, camlQuery);
  //       //
  //       var array = []
  //       Naturcontract1.forEach(async element => {
  //         // 仅申请书表
  //         var param1 = {
  //           Guid: ListGUID.Petition, //表数据
  //           Filter: `ItemBelong eq '0' and Title eq '${element.Title}'`
  //         };
  //         let filterlist = await Api._getModel(param1);
  //         if (filterlist.length != 0) {
  //           array.push(filterlist[0])
  //         }
  //       });
  //       this.state.time3 = setTimeout(async () => {
  //         var updateList = await Api._getPermissionData(ListGUID.Petition, array)
  //         updateList.forEach(async element => {
  //           element.ContractName = element.filename
  //           element.Counterparty = element.company_name
  //           if (element.SRUrls != null) {
  //             let index = element.SRUrls.lastIndexOf("/")
  //             element.SRUrls = element.SRUrls.substring(0, index);
  //             //
  //             let file = await Api.getFiles(element.SRUrls);
  //             element.file = file
  //           } else {
  //             let file = []
  //             element.file = file
  //           }
  //           // return
  //         });

  //         ToTheTotal = this.state.data.concat(updateList)
  //         //
  //         let arr = ToTheTotal
  //         //
  //         this.setState({
  //           data: arr,
  //           totalnum: arr.length,
  //           loading: false,
  //           inSearchOf: false
  //         })
  //       }, 300)
  //       this.state.time2 = setTimeout(() => {

  //       }, 1000)
  //       //
  //     } else {
  //       //
  //       let array = []
  //       array.push(new CamlParam("ItemBelong", '0', SPDataType.Number, CAMLCompare.Eq));//查询合同申请书

  //       let camlQuery = {
  //         ViewXml: ''
  //       }
  //       //不排序
  //       let demo = Api.buildCamlXml(array);

  //       let Guid = ListGUID.Petition //根据条件检索表数据

  //       camlQuery.ViewXml = demo

  //       let Naturcontract1 = await Api.GetListItemsByCAMLQuery(Guid, camlQuery);
  //       let updateList = await Api._getPermissionData(ListGUID.Petition, Naturcontract1)
  //       //
  //       updateList.forEach(async element => {
  //         //
  //         element.ContractName = element.filename
  //         element.Counterparty = element.company_name
  //         if (element.SRUrls != null) {
  //           let index = element.SRUrls.lastIndexOf("/")
  //           element.SRUrls = element.SRUrls.substring(0, index);
  //           //
  //           let file = await Api.getFiles(element.SRUrls);
  //           element.file = file
  //         } else {
  //           let file = []
  //           element.file = file
  //         }
  //         // return
  //       });

  //       this.state.time1 = setTimeout(() => {
  //         ToTheTotal = this.state.data.concat(updateList)
  //         let arr = ToTheTotal
  //         //
  //         this.setState({
  //           data: arr,
  //           totalnum: arr.length,
  //           loading: false,
  //           inSearchOf: false
  //         })
  //       }, 300)
  //     }
  //   }
  // }

  // 切换分页
  public async ontab(e) {

    let size = e * 10 - 10
    // //
    // 追加附件的数据数量
    let num = 10
    let arr = []
    for (let i = 0; i < num; i++) {
      // //
      arr.push(this.state.data[size])
      size++
    }

    arr.forEach(async element => {

      if (element.SRUrls = undefined) {
        if (element.FileAddress != null) {
          let file = await Api.getFiles(ListGUID.ContractLibRelativeUrl + '/' + element.FileAddress);
          element.file = file
        } else {
          element.file = []
        }
      } else {
        if (element.SRUrls != null) {
          let index = element.SRUrls.lastIndexOf("/")
          element.SRUrls = element.SRUrls.substring(0, index);

          let file = await Api.getFiles(element.SRUrls);
          element.file = file
        } else {
          let file = []
          element.file = file
        }
      }

    });

    // //
    // //


  }

}
export default Form.create()(SearchContract);
